<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/css.css" rel="stylesheet" type="text/css" />
<link href="css/common.css" rel="stylesheet" type="text/css" />
<link href="css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery.min.1.8.2.js" type="text/javascript"></script>
<script src="js/jquery.SuperSlide.2.1.1.js" type="text/javascript"></script>
<script type="text/javascript" src="js/slide.js"></script>
<script src="js/common_js.js" type="text/javascript"></script>
<script src="js/jquery.foucs.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery-3.6.0.min.js"></script>
		<script type="text/javascript" src="js/axios.min.js"></script>
<title>购物车</title>
</head>
<script>
	const phone=sessionStorage.getItem("phone");
	$(document).ready(function() {
	    // 页面加载时检查sessionStorage是否有phone值
	    var storedPhone = sessionStorage.getItem('phone');
	    if (storedPhone) {
	        // 如果有，将其插入到id为"login_info"的元素中
	        $('#login_info').text(storedPhone);
	    }
		searchCartList(phone);
	});
	
	// 查询购物车
	const searchCartList = (phone) => {
	    axios.get("http://localhost:8080/consumer/cartList",  { 
        params: { phone },
		}).then((response) => {
	        console.log(response.data);
			data=response.data;
			length=data.length;
			console.log(data.length)
			fun();
	    }).catch(error => {
	        console.error("获取购物车信息失败:", error);
	    });
}
		   function fun() {
		       var str = '<div class="list_style" id="cartList">';
		       str += '<div class="class_title" id="cartListTitle">购物车</div>';
		       for (var i = 0; i < data.length; i++) {
		           str += '<ul class="product_cart" id="cartItem_' + i + '">';
		           // str += ' <li class="title_width"><input type="checkbox" id="checkbox_' + i + '"></li>';
		           str += ' <li class="title_width1">';
		           str += ' <a href="#" class="product_img left"><img src="' + data[i].image_url + '" /></a>';
		           str += ' <p class="cart_content">';
		           str += '<a href="#" class="title_name">' + data[i].product_name + '</a>';
		           str += '<span>' + data[i].description + '</span> </p></li>';
		           str += ' <li class="title_width2">' + data[i].price + '</li>';
		           str += ' <li class="title_width3"><div class="Numbers">';
		           str += ' <a href="javascript:void(0);" onclick="updatenum(' + i + ', \'decrease\');" class="jian">-</a>';
		           str += ' <input id="number_' + i + '" name="number" type="text" value="' + data[i].number + '" class="number_text">';
		           str += '<a href="javascript:void(0);" onclick="updatenum(' + i + ', \'increase\');" class="jia">+</a></div>';
		           str += '</li>';
		           str += '<li class="title_width4" id="subtotal_' + i + '">' + (data[i].price * data[i].number).toFixed(2) + '</li>'; // 初始化小计
		           str += '<li class="title_width5"><button class="delete-btn" onclick="deleteFormList('+data[i].shopping_cart_id +')">删除</button></li>';
		           str += '</li>'
				   str += '</ul>';
		       }
		       str += '</div>';
		       $("#cartList").html(str);
		      
		       for (var j = 0; j < data.length; j++) {
		           updateSubtotal(j);
		       }
			    // 初始化总价计算
			calculateTotalPrice();
		   }

function updatenum(index, operation) {
    var currentNumber = parseInt($("#number_" + index).val());
    if (operation === 'increase') {
        $("#number_" + index).val(currentNumber + 1);
    } else if (operation === 'decrease' && currentNumber > 1) {
        $("#number_" + index).val(currentNumber - 1);
    }
     updateSubtotal(index);
     calculateTotalPrice(); // 数量变化后重新计算总价
}

function updateSubtotal(index) {
    var number = parseInt($("#number_" + index).val());
    var price = parseFloat(data[index].price);
    var subtotal = number * price;
    $("#" + "subtotal_" + index).text(subtotal.toFixed(2)); // 更新小计显示
}

// 新增实时计算总价并更新DOM的功能
function calculateTotalPrice() {
    var totalPrice = 0;
    for (var i = 0; i < data.length; i++) {
        var number = parseInt($("#number_" + i).val());
        var price = parseFloat(data[i].price);
        totalPrice += number * price;
    }
    // 更新页面上的商品总价显示
    $(".cart_price b").text(totalPrice.toFixed(2));
}
   // 删除购物车中列表
	const deleteFormList = (id) => {
	    axios.get("http://localhost:8080/cart/deleted",  { 
        params: { id },
		}).then((response) => {
			console.log(response.data);
	        if(response.data){
				alert("删除成功");
				searchCartList(phone);
			}			
	    }).catch(error => {
	        console.error("获取购物车信息失败:", error);
	    });
}


// $(document).ready(function() {
//     // 点击去支付按钮的事件处理
//     $(".payment_btn").click(function(event) {
//         event.preventDefault(); // 阻止默认行为
        
//         // 收集被选中的商品索引和数量
//         var itemsToUpdate = [];
//         $("input[type='checkbox']:checked").each(function() {
//             var index = $(this).attr("id").slice(-1); // 获取索引
//             var number = parseInt($("#number_" + index).val()); // 获取数量
//             itemsToUpdate.push({ shoppingCartId: data[index].shopping_cart_id, quantity: number });
//         });

//         // 如果有商品被选中，则发起更新请求
//         if (itemsToUpdate.length > 0) {
//             updateCartQuantities(itemsToUpdate);
//         } else {
//             alert("请至少选择一项商品进行支付");
//         }
//     });
// });

// // 更新购物车商品数量的函数
// function updateCartQuantities(items) {
//     axios.post("http://localhost:8080/consumer/updateCartQuantities", items)
//         .then((response) => {
//             console.log(response);
//             if (response.data.success) {
//                 alert("购物车商品数量更新成功！");
               
//             } else {
//                 alert(response.data.message || "更新购物车数量时发生错误，请重试。");
//             }
//         })
//         .catch((error) => {
//             console.error("更新购物车数量失败:", error);
//             alert("网络错误，请检查网络连接。");
//         });
// }

function makeOrder(){
    fetch("http://localhost:8080/order/make", {method:"GET",
        headers:{
            'Content-Type':'application/json',
            'token':sessionStorage.getItem("token"),
        },
    })
    .then(response => {
        if(!response.ok){
            throw new Error('请求失败');
        }
        // 解析响应体为JSON
        return response.json();
    })
    .then(data => {
        if(data && data.orderNumber){
            // alert(data.orderNumber);
            alert("即将前往支付页面");
            window.location.href="Orders.html";
        }else{
            alert("下单失败");
        }
    })
    .catch(error => {
        console.error('发生错误:', error);
        alert("下单过程中发生错误，请重试");
    });
}



</script>
<body>
<!--顶部样式-->
<div class="top_header">
<em class="left_img"></em>
<div class="header clearfix" id="header">

<div class="header_Section">
 <div class="shortcut">
  <ul>
    <li  class="hd_menu_tit"><a href="user_info.html" id="login_info"></a></li>
   <li  class="hd_menu_tit"><em class="Collect_img"></em><a href="#">收藏夹</a></li>
  </ul>
 </div>
 <div class="nav" id="Navigation">
  <ul class="Navigation_name"> 
  <ul class="Navigation_name"> 
   <li class=""><a href="index.html">首页</a></li>
   <li class=""><a herf="#">浆果类专区</a></li>
   <li class=""><a herf="#">核果类专区</a></li>
   <li class=""><a herf="#">温性水果专区</a></li>
   <li class=""><a herf="#">仁果专区</a></li>
   <li class=""><a herf="#">联系我们</a></li>
  </ul>
 </div>

</div>
</div>
<em class="right_img"></em>
</div>
<!---->
<div></div>
<!--位置-->
<div class="Bread_crumbs">
 <div class="Inside_pages clearfix">
   <div class="right Search">
   <form>
    <input name="" type="text"  class="Search_Box"/>
    <input name="" type="button"  name="" class="Search_btn"/>
    </form>
   </div>
 </div>
</div>
<!--购物车样式-->
<div class="Narrow">
  <div class="shop_cart">
     <div class="schedule"></div>
     <div class="cart_style">
       <div class="title_name">
        <ul>
         <li class="title_width"><label class="auto-label"></label></li>
         <li class="title_width1">商品信息</li>
         <li class="title_width2">单价</li>
         <li class="title_width3">数量</li>
         <li class="title_width4">小计</li>
         <li class="title_width5">操作</li>
        </ul>
       </div>
	   
	   
       <div class="list_style" id="cartList">
        <div class="class_title" >水果馆</div>
         <ul class="product_cart">
         <li class="title_width"></li>
         <li class="title_width1">
         <a href="#" class="product_img left"><img src="images/product_img_17.png" /></a>
         <p class="cart_content">
         <a href="#" class="title_name">浦江特产绿豌豆天然无污染</a>
         <span> 礼盒装：20个装</span>
         </p>
         </li>
         <li class="title_width2">￥23</li>
         <li class="title_width3">
           <div class="Numbers">
		  <a href="javascript:void(0);" onclick="updatenum('del');" class="jian">-</a>
		  <input id="number" name="number" type="text" value="1" class="number_text">
		  <a href="javascript:void(0);" onclick="updatenum('del');" class="jia">+</a>
		 </div>        
         </li>
         <li class="title_width4">￥545</li>
         <li class="title_width5"><a href="#">删除</a></li>
         </ul>
         <ul class="product_cart">
         <li class="title_width"><input type="checkbox" id="rememberMe"></li>
         <li class="title_width1">
         <a href="#" class="product_img left"><img src="images/product_img_17.png" /></a>
         <p class="cart_content">
         <a href="#" class="title_name">浦江特产绿豌豆天然无污染</a>
         <span> 礼盒装：20个装</span>
         </p>
         </li>
         <li class="title_width2">￥23</li>
         <li class="title_width3">
           <div class="Numbers">
		  <a href="javascript:void(0);" onclick="updatenum('del');" class="jian">-</a>
		  <input id="number" name="number" type="text" value="1" class="number_text">
		  <a href="javascript:void(0);" onclick="updatenum('del');" class="jia">+</a>
		 </div>        
         </li>
         <li class="title_width4" id="totalPrice">￥545</li>
         <li class="title_width5"><a href="#" onclick="deleteFormList()">删除</a></li>
         </ul>
       </div>
              <div class="list_style">
     </div>
     <!--操作-->
     <div class="cart_operating clearfix">
        <div class="cart_operating_style">
           <div class="cart_price">商品总价：（不含运费）<b>￥545</b></div>
		 <div class="cart_operating clearfix">
		     <div class="cart_operating_style">
		         <!-- ... -->
		         <div class="cart_btn">
		             <a href="#" class="payment_btn" onclick="makeOrder()"></a>
		             <a href="#" class="continue_btn"></a>
		         </div>
		     </div>
		 </div>
           <!-- <div class="cart_btn"><a href="Orders.html" class="payment_btn"></a><a href="#" class="continue_btn"></a></div> -->
        </div>
     </div>
  </div>
</div>
<!--底部样式-->
<div class="footer">
 <div class="footer_img_bg"></div>
 <div class="footerbox">
  <div class="footer_info">
  </div>
 </div> 
</div>
</body>
<style>
	.delete-btn {
	    background-color: #f00; 
	    color: #fff;
	    border: none;
	    padding: 5px 10px;
	    cursor: pointer;
	    text-align: center;
	    text-decoration: none;
	    display: inline-block;
	    font-size: 14px;
	    margin: 4px 2px;
	    border-radius: 4px;
	}
</style>
</html>
